<?php

namespace app\common\model;

use think\Db;
use think\Model;

class VideoOrder extends Model

{
    // 表名
    protected $name = 'video_order';


    /**
     * 支付回调
     */
    public function notify_order($orderNo, ?string $pay_sn = '', ?string $payMoney = '0')
    {
        $info = self::where('order_sn', $orderNo)->find();
        if (!$info) fail("订单不存在");
        if ($info['status'] == '1') fail("订单已支付");

        $info->status = '1';
        $info->pay_time = time();
        # 微信流水号
        if ($pay_sn) {
            $info->pay_sn = $pay_sn;
            $info->pay_money = $payMoney;
        }
        $video = Db::name('video')->where('id', $info['video_id'])->field('teacher_id,day')->find();
        # 更新视频课资源
        $uservodeo = new UserVideo();
        $uservodeo->saveUserVideo($info['user_id'], $info['video_id'], $video['teacher_id'], $video['day']);
        $info->save();
        return true;
    }


    /**
     * 我的订单
     */
    public function getOrderList($where, $user_id)
    {
        $list = self::alias('vo')
            ->join('video v', 'vo.video_id=v.id')
            ->where(function ($query) use ($where, $user_id) {
                if (isset($where['status']) && $where['status'] >= 0) {
                    $query->where('vo.status', $where['status']);
                }
                if ($user_id) {
                    $query->where('vo.user_id', $user_id);
                }
            })
            ->field('vo.id as order_id ,vo.order_sn,vo.money,vo.status,vo.createtime,v.name,v.label,v.image')
            ->select();
            foreach ($list as  &$v) {
                $v['label'] = $v['label'] ?explode(',', $v['label']) : [];
            }
        return $list;
    }
}
